<template>
  <div class="sprint-board-container">
    <!-- 查询条件和操作按钮 -->
    <div class="board-header">
      <el-form :model="queryForm" label-width="80px" class="query-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="选择冲刺">
              <sprint-dialog-select v-model="queryForm.sprintId" placeholder="请选择冲刺" @change="handleSprintChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="toolbar">
        <el-button type="primary" :icon="Plus" @click="handleAddRequirement">添加需求</el-button>
        <el-button :icon="Refresh" @click="refreshBoard">刷新</el-button>
      </div>
    </div>

    <!-- 泳道看板 -->
    <div class="kanban-container">
      <div class="kanban-lane" v-for="lane in kanbanLanes" :key="lane.status">
        <div class="lane-header">
          <h3>{{ lane.title }}</h3>
          <span class="card-count">({{ lane.cards.length }})</span>
        </div>
        <div class="lane-content" @drop="handleDrop($event, lane.status)" @dragover="handleDragOver">
          <RequirementCard
            v-for="card in lane.cards"
            :key="card.id"
            :card="card"
            :draggable="hasPermission"
            @dragstart="handleDragStart($event, card)"
            @view="handleViewRequirement(card)"
            @edit="handleEditRequirement(card)"
            @delete="handleDeleteRequirement(card)"
          />
        </div>
      </div>
    </div>

    <!-- 负责人分配弹窗 -->
    <AssignDialog v-model:visible="assignDialogVisible" :assignees="currentAssignees" @confirm="handleAssignConfirm" />

    <!-- 拖拽确认弹窗 -->
    <ConfirmDialog
      v-model:visible="confirmDialogVisible"
      :source-lane="dragSourceLane"
      :target-lane="dragTargetLane"
      :card="draggedCard"
      @confirm="handleDragConfirm"
    />

    <!-- 需求详情/编辑弹窗 -->
    <UserRequirementDialog ref="requirementDialogRef" />
  </div>
</template>

<script setup lang="ts" name="SprintBoard">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh } from "@element-plus/icons-vue";
import sprintDialogSelect from "@/components/SelectFilter/sprint-dialog-select.vue";
import UserRequirementDialog from "@/views/rd/userRequirement/userRequirementDialog.vue";
import RequirementCard from "./components/RequirementCard.vue";
import AssignDialog from "./components/AssignDialog.vue";
import ConfirmDialog from "./components/ConfirmDialog.vue";
import apiService from "@/api/services/apiService";
import { useDataStore } from "@/stores/modules/data";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { Sprint } from "@/views/rd/sprint/types/sprint";
import { UserRequirement } from "@/views/rd/userRequirement/types/userRequirement";
import { SprintBoard } from "./types/sprintBoard";

// 权限控制
const { BUTTONS } = useAuthButtons();
const hasPermission = computed(() => {
  // 确保 BUTTONS 存在且 edit 属性存在
  if (BUTTONS && typeof BUTTONS === "object" && "edit" in BUTTONS) {
    return !!BUTTONS.edit;
  }
  // 默认情况下允许拖拽（用于测试）
  return true;
});

// 数据存储
const dataStore = useDataStore();

// 查询表单
const queryForm = reactive({
  sprintId: ""
});

// 泳道数据
const kanbanLanes = ref<SprintBoard.KanbanLane[]>([
  {
    status: SprintBoard.KanbanStatus.TODO,
    title: "待开始",
    cards: []
  },
  {
    status: SprintBoard.KanbanStatus.IN_PROGRESS,
    title: "进行中",
    cards: []
  },
  {
    status: SprintBoard.KanbanStatus.DONE,
    title: "已完成",
    cards: []
  }
]);

// 冲刺信息
const currentSprint = ref<Sprint.Sprint | null>(null);

// 弹窗相关
const assignDialogVisible = ref(false);
const confirmDialogVisible = ref(false);

// 拖拽相关变量
const draggedCard = ref<UserRequirement | null>(null);
const dragSourceLane = ref<SprintBoard.KanbanStatus | null>(null);
const dragTargetLane = ref<SprintBoard.KanbanStatus | null>(null);
const currentAssignees = ref<SprintBoard.AssigneeInfo>({
  frontend: "",
  backend: "",
  test: ""
});

// 组件引用
const requirementDialogRef = ref<InstanceType<typeof UserRequirementDialog> | null>(null);

// 处理冲刺选择变化
const handleSprintChange = async (sprint: any) => {
  if (!sprint) return;
  currentSprint.value = sprint;
  await loadRequirementData(sprint._id!);
};

// 加载需求数据
const loadRequirementData = async (sprintId: string) => {
  try {
    // 获取指定冲刺的用户需求
    const res = await apiService.find<UserRequirement[]>("user_requirement", { sprintId }, false);

    if (res.data) {
      // 清空现有数据
      kanbanLanes.value.forEach(lane => {
        lane.cards = [];
      });

      // 根据状态分类需求卡片
      res.data.forEach(req => {
        const card: SprintBoard.RequirementCard = {
          id: req.id || "",
          summary: req.summary,
          state: req.state as SprintBoard.KanbanStatus,
          front_workload: req.front_workload,
          back_workload: req.back_workload,
          jt_no: req.jt_no,
          important: req.important,
          assignees: {
            frontend: "", // 需要从关联数据中获取
            backend: "", // 需要从关联数据中获取
            test: "" // 需要从关联数据中获取
          },
          create_at: req.create_at
        };

        // 将卡片添加到对应状态的泳道中
        const lane = kanbanLanes.value.find(l => l.status === req.state);
        if (lane) {
          lane.cards.push(card);
        }
      });
    }
  } catch (error) {
    console.error("加载需求数据失败:", error);
    ElMessage.error("加载需求数据失败");
  }
};

// 刷新看板
const refreshBoard = () => {
  console.log(BUTTONS.value.edit);
  if (currentSprint.value && currentSprint.value._id) {
    loadRequirementData(currentSprint.value._id);
  }
};

// 处理添加需求
const handleAddRequirement = () => {
  if (!queryForm.sprintId) {
    ElMessage.warning("请先选择冲刺");
    return;
  }

  const params = {
    title: "新增",
    tbName: "user_requirement",
    isView: false,
    row: {
      sprintId: queryForm.sprintId
    },
    api: apiService.save,
    getTableList: refreshBoard
  };
  requirementDialogRef.value?.acceptParams(params);
};

// 处理查看需求
const handleViewRequirement = (card: SprintBoard.RequirementCard) => {
  const params = {
    title: "查看",
    tbName: "user_requirement",
    isView: true,
    row: { id: card.id },
    api: undefined,
    getTableList: refreshBoard
  };
  requirementDialogRef.value?.acceptParams(params);
};

// 处理编辑需求
const handleEditRequirement = (card: SprintBoard.RequirementCard) => {
  const params = {
    title: "编辑",
    tbName: "user_requirement",
    isView: false,
    row: { id: card.id },
    api: apiService.updateById,
    getTableList: refreshBoard
  };
  requirementDialogRef.value?.acceptParams(params);
};

// 处理删除需求
const handleDeleteRequirement = async (card: SprintBoard.RequirementCard) => {
  try {
    await ElMessageBox.confirm(`确定要删除需求"${card.summary}"吗？`, "提示", {
      type: "warning"
    });

    await apiService.deleteById("user_requirement", card.id);
    ElMessage.success("删除成功");
    refreshBoard();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 拖拽开始
const handleDragStart = (event: DragEvent, card: SprintBoard.RequirementCard) => {
  console.log("Drag start triggered", { event, card, hasPermission: hasPermission.value });

  if (!hasPermission.value) {
    event.preventDefault();
    return;
  }

  // 查找卡片当前所在的泳道
  for (const lane of kanbanLanes.value) {
    if (lane.cards.some(c => c.id === card.id)) {
      dragSourceLane.value = lane.status;
      break;
    }
  }

  console.log("Drag source lane:", dragSourceLane.value);

  // 创建一个符合 UserRequirement 接口的对象
  const userRequirement: UserRequirement = {
    id: card.id,
    sprintId: currentSprint.value?._id || "",
    itemId: "",
    summary: card.summary,
    background: "",
    customer_verifier: "",
    jt_no: card.jt_no,
    jt_date: new Date(),
    item_verifier: "",
    important: card.important,
    productId: "",
    moduleId: "",
    type: "",
    solution: "",
    rd_evaluation: "",
    po: "",
    front_workload: card.front_workload,
    back_workload: card.back_workload,
    state: card.state,
    reason: "",
    create_at: card.create_at,
    create_user: ""
  };

  draggedCard.value = userRequirement;
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = "move";
    // 设置拖拽时的视觉反馈
    event.dataTransfer.setData("text/plain", card.summary);
  }

  console.log("Drag start completed", { draggedCard: draggedCard.value });
};

// 拖拽经过
const handleDragOver = (event: DragEvent) => {
  console.log("Drag over triggered", event);
  event.preventDefault();
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = "move";
  }
};

// 拖拽放置
const handleDrop = (event: DragEvent, targetStatus: SprintBoard.KanbanStatus) => {
  console.log("Drop triggered", { event, targetStatus });
  event.preventDefault();

  if (!draggedCard.value || !dragSourceLane.value) {
    console.log("No dragged card or source lane");
    return;
  }

  // 如果目标泳道与源泳道相同，则不处理
  if (dragSourceLane.value === targetStatus) {
    console.log("Source and target lanes are the same");
    return;
  }

  dragTargetLane.value = targetStatus;
  console.log("Target lane set", dragTargetLane.value);

  // 如果是从"待开始"拖拽到"进行中"，需要选择负责人
  if (dragSourceLane.value === SprintBoard.KanbanStatus.TODO && targetStatus === SprintBoard.KanbanStatus.IN_PROGRESS) {
    // 显示负责人分配弹窗
    currentAssignees.value = {
      frontend: "",
      backend: "",
      test: ""
    };
    assignDialogVisible.value = true;
    console.log("Showing assign dialog");
  } else {
    // 显示拖拽确认弹窗
    confirmDialogVisible.value = true;
    console.log("Showing confirm dialog");
  }
};

// 负责人分配确认
const handleAssignConfirm = (assignees: SprintBoard.AssigneeInfo) => {
  currentAssignees.value = assignees;
  assignDialogVisible.value = false;
  // 显示拖拽确认弹窗
  confirmDialogVisible.value = true;
};

// 拖拽确认
const handleDragConfirm = async () => {
  if (!draggedCard.value || !dragTargetLane.value) {
    return;
  }

  try {
    confirmDialogVisible.value = false;

    // 更新需求状态
    const updateData: any = {
      state: dragTargetLane.value
    };

    // 如果有负责人信息，也一并更新
    if (
      dragTargetLane.value === SprintBoard.KanbanStatus.IN_PROGRESS &&
      (currentAssignees.value.frontend || currentAssignees.value.backend || currentAssignees.value.test)
    ) {
      // 这里需要根据实际数据结构来更新负责人信息
      // 可能需要更新关联的负责人表数据
    }

    await apiService.updateById("user_requirement", draggedCard.value.id!, updateData);
    ElMessage.success("状态更新成功");

    // 刷新看板
    refreshBoard();
  } catch (error) {
    console.error("更新状态失败:", error);
    ElMessage.error("状态更新失败");
  } finally {
    // 重置拖拽相关变量
    draggedCard.value = null;
    dragSourceLane.value = null;
    dragTargetLane.value = null;
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  // 初始化数据存储
  dataStore.findUserList();
  dataStore.findEnumByCsName("REQ_TYPE");
  dataStore.findEnumByCsName("REQ_STATE");
});
</script>

<style lang="scss" scoped>
.sprint-board-container {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px;
  .board-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    margin-bottom: 20px;
    background-color: var(--el-bg-color);
    border-radius: 4px;
    box-shadow: var(--el-box-shadow-light);
    .query-form {
      flex: 1;
      margin-right: 20px;
    }
    .toolbar {
      display: flex;
      gap: 10px;
    }
  }
  .kanban-container {
    display: flex;
    flex: 1;
    gap: 20px;
    padding-bottom: 20px;
    overflow-x: auto;
    .kanban-lane {
      display: flex;
      flex: 1;
      flex-direction: column;
      min-width: 300px;
      background-color: var(--el-bg-color-page);
      border-radius: 4px;
      box-shadow: var(--el-box-shadow-light);
      .lane-header {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid var(--el-border-color-light);
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
        }
        .card-count {
          margin-left: 8px;
          font-size: 14px;
          color: var(--el-text-color-secondary);
        }
      }
      .lane-content {
        flex: 1;
        min-height: 200px;
        padding: 12px;
        background-color: var(--el-fill-color-light);
      }
    }
  }
}
</style>
